<template>
  <div class="comment-list">
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      :error="error"
      error-text="加载失败，请点击重试"
      @load="onLoad"
    >
      <!-- :title="item.content" -->
      <comment-item v-for="(item, index) in list" :key="index"
       :comment="item"
      />
    </van-list>
  </div>
</template>

<script>
import { getCommentsAPI } from '../../../api/index.js'
import CommentItem from './comment-item.vue'
export default {
  name: 'CommentList',
  components: {
    CommentItem
  },
  props: {
    sourceId: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      list: [],
      loading: false,
      finished: false,
      offset: null, // 请求下一页数据的页码
      error: false
    }
  },
  // created () {
  //   this.onLoad()
  // },
  methods: {
    async onLoad () {
      try {
        // 1. 请求获取数据
        const { data: res } = await getCommentsAPI({
          type: 'a', // 评论类型，a-对文章(article)的评论，c-对评论(comment)的回复
          source: this.sourceId.toString(), // 源id，文章id或评论id
          offset: this.offset,
          limit: 5 // 每页大小
        })
        // 2. 将数据添加到列表中
        this.list.push(...res.data.results)

        this.$emit('onload-success', res.data.total_count)
        // 3. 将加载更多的 loading 设置为 false
        this.loading = false

        // 4. 判断是否还有数据
        if (res.data.results.length) {
          this.offset = res.data.last_id // 更新获取下一页数据的页码
        } else {
          this.finished = true // 没有数据了，关闭加载更多
        }
      } catch (error) {
        this.error = true
        this.loading = false
      }
    }
  }
}
</script>

<style lang="less" scoped>
</style>
